<script setup lang="ts">
import {
  ref,
  defineProps,
  watch,
  defineEmits,
  computed,
  getCurrentInstance,
} from "vue";
import { showImagePreview } from 'vant';
const emits = defineEmits<{
  (e: "getImgData", val: string[], key: string,mode:string): void;
}>();
//定义props
const propsData = defineProps<{
  isRequire?: boolean;
  name: string;
  imgData: string[];
  keyName: string;
  max?: number;
}>();
const { proxy } = getCurrentInstance() as any;
//判断上传按钮是否隐藏
const showUpload = computed(() => propsData.max ?? 100);

//定义图片组
const fileList =ref<string[]>([]);
//定义图片预览
const show = ref(false);
const imgIndex = ref(0);
function preview(val: number,data:string[]): void {
  // console.info(val);
  show.value = true;
  imgIndex.value = val;


  showImagePreview({
    images:data,
    startPosition: val
  });



}



watch(
  () => propsData.imgData,
  (newVal) => {
    // console.info(newVal)
    fileList.value = [];
    if (propsData.imgData) {
      propsData.imgData.forEach((val) => {
        fileList.value.push(val);

      });
    }
  },{deep:true,immediate:true}
);


//上传图片之后
function afterRead(file:any) {

  // console.info(file);
  proxy.$imgCompress(file.file).then((resInfo: string[]) => {
    emits("getImgData", resInfo, propsData.keyName,'add');
    
  });
}
//删除图片后
function deletes(index: number) {
  let imgDatas = JSON.parse(JSON.stringify(fileList.value));
  imgDatas.splice(index, 1);
  fileList.value = imgDatas;
  emits("getImgData", fileList.value, propsData.keyName,'del');
}
</script>

<template>
  <div class="">
    <div class="title" :class="[isRequire ? 'isRequire' : '']">
      {{ name }}：
    </div>
    <div class="imgContinal">
      <div
        class="imgbox"
        @click="preview(index,fileList)"
        v-for="(item, index) in fileList"
        :key="index"
      >
        <img :src="item" />
        <van-icon
          class="del"
          name="clear"
          color="red"
          @click.stop="deletes(index)"
        />
      </div>
      <div>
        <van-uploader
          multiple
          :after-read="afterRead"
          v-show="fileList.length < showUpload"
        />
      </div>
    </div>
   
  </div>
</template>

<style lang="scss" scoped>
.title {
  color: #666666;
  margin-bottom: 10px;
  font-size: 16px;
  position: relative;
}
.isRequire:before {
  content: "*";
  position: absolute;
  color: red;
  left: -9px;
  top: 50%;
  transform: translateY(-50%);
}
.imgContinal {
  @include imgContinal();
  .imgbox {
    position: relative;
    .del {
      position: absolute;
      z-index: 10;
      right: -7px;
      top: -5px;
    }
  }
}

::v-deep .van-uploader__upload {
  margin-bottom: 10px;
}
</style>
